/**
 * Created by panjun7@yunzongnet.com on 2016/10/25.
 */
var isHaveShop = true;
var showManageanalyze = false;
IndexController = function () {
    this.indexPageCountSprice='';
    var self = this;
    this.diagnosisList = [];
    this.configInfo = {
        "createActPageUrl": {
            "43": "activity_create_new_sm.html",//挽回流失会员
            "46": "activity_create_new_sm.html",//新会员招募
            "51": "activity_create_consume_sm.html",//消费送圈人活动
            "22": "activity_create_consume_sm.html",//消费送
            "25": "create_activity_xhyzm.html"//扫码送
        },
        "diagnoseOrder": {
            "2": 1,
            "3": 2,
            "1": 3
        },
        "diagnoseTitle": {
            "rate>=70": {
                "1": "会员流失严重",
                "2": "新会员严重缺失",
                "3": "回头客严重不足"
            },
            "rate>30 && rate<70": {
                "1": "会员流失过多",
                "2": "新会员过少",
                "3": "回头客过少"
            },
            "rate<=30": {
                "1": "会员流失较多",
                "2": "新会员不足",
                "3": "回头客较少"
            }
        },
        "minus": {
            "app.home": {
                className: "active",
                needRefresh: 'true',
                triggerEvent: 'refreshHome',
                id: "index",
                className1: "zhk-tab_home",
                className2: "zhk-tab_home_active",
                name: "首页"
            },
            "app.marketingcenter": {
                className: "",
                id: "activity",
                className1: "zhk-tab_yx",
                className2: "zhk-tab_yx_active",
                name: "营销中心"
            },
            "app.order": {
                className: "",
                id: "order",
                className1: "zhk-tab_order",
                className2: "zhk-tab_order_active",
                name: "订单"
            },
            "app.my": {
                className: "",
                id: "my",
                className1: "zhk-tab_user",
                className2: "zhk-tab_user_active",
                name: "我的"
            }
        }
    };
    this.getSplitNumberCompany=function(string){
        var str = string;
        var arr = new Array();
        var i = 0;
        while (i<str.length) {
            var s="";
            while (str.charCodeAt(i) < 256) {
                s=s+str.charAt(i);
                i++;
            }
            arr.push(s);
            var s="";
            while (str.charCodeAt(i) > 256) {
                s=s+str.charAt(i);
                i++;
            }
            arr.push(s);
        }
        return arr;
    }
    this.getTrendConfig = function () {
        return {
            yAxisNames: { todayPayAmt: '单位:元' },
            legendData: {
                todayPayAmt: ['实收金额'],
            },
            seriesNames: {
                todayPayAmt: ['实收金额'],
            },
            option: {
                title: {
                    x: "center"
                },
                tooltip: {
                    trigger: "axis",
                    formatter: function (param) {
                        if (param.length == 1) {
                            if (typeof (param[0].value) == "undefined") {
                                return "时间:" + param[0].name + "<br>" + param[0].seriesName + ":0";
                            } else {
                                return "时间:" + param[0].name + "<br>" + param[0].seriesName + ":" + (param[0].value);
                            }
                        } else if (param.length == 2) {
                            if (typeof (param[0].value) == "undefined" && typeof (param[1].value) == "undefined") {
                                return "时间:" + param[0].name + "<br>" + param[0].seriesName + ":0" + "<br>" + param[1].seriesName + ":0";
                            } else {
                                return "时间:" + param[0].name + "<br>" + param[0].seriesName + ":" + (param[0].value) + "<br>" + param[1].seriesName + ":" + (param[1].value);
                            }
                        }

                    }
                },
                grid: {
                    width: '90%',
                    left: '3%',
                    right: '4%',
                    bottom: '2%',
                    containLabel: true
                },
                calculable: true,
                legend: {
                    orient: 'horizontal',
                    data: [],
                    selectedMode: 'single'
                },
                xAxis: [
                    {
                        type: "category",
                        name: "",
                        boundaryGap: false,
                        data: [],
                        splitLine: {
                            boundaryGap: false,
                            lineStyle: {
                                color: "#dbdbdb"
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: "#a7a7a7"
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: "#a7a7a7"
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: "#a7a7a7"
                            }
                        }
                    }
                ]
                ,
                yAxis: [
                    {
                        type: "value",
                        scale: true,
                        //                     splitNumber:5,
                        name: "",
                        splitLine: {
                            boundaryGap: false,
                            lineStyle: {
                                color: "#dbdbdb"
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: "#a7a7a7"
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: "#a7a7a7"
                            }
                        },
                        axisLabel: {
                            formatter: function (v) {
                                return v;
                            },
                            textStyle: {
                                color: "#a7a7a7"
                            }
                        }
                    }
                ]
                ,
                calculable: true,
                series: [
                    {
                        name: "会员总数",
                        type: "line",
                        data: [],
                        //stack:"总量",
                        areaStyle: { normal: {} }

                    },
                    {
                        name: "新增会员数",
                        type: "line",
                        data: [],
                        //stack:"总量",
                        areaStyle: { normal: {} }

                    }
                ],
                color: ['#2eb6f5', '#ff6600']
            }
        }
    }

    this.parseDiagnostTitle = function (diagnoseItem) {
        for (var rule in this.configInfo.diagnoseTitle) {
            var el = rule.replace(/rate/g, diagnoseItem.industryRate);
            if (eval(el)) {
                return this.configInfo.diagnoseTitle[rule][diagnoseItem.diagnoseCode];
            }
        }
    };
    this.adaptDiagnoseData = function (result) {
        var warningContent = [];
        var recommendedActs = [];
        var self = this;
        var totalStartActCnt = 0;
        if (result.diagnosisList && result.diagnosisList.length > 0) {
            for (var i = 0; i < result.diagnosisList.length; i++) {
                var diagnosisItem = result.diagnosisList[i];
                var act = { "diagnoseCode": diagnosisItem.diagnoseCode };
                totalStartActCnt += parseInt(diagnosisItem.hasStartActCnt);

                //存在进行中的活动就不允许继续创建
                if (parseInt(diagnosisItem.hasStartActCnt) > 0) {
                    continue;
                }


                act.diagnoseTitle = self.parseDiagnostTitle(diagnosisItem);
                if (diagnosisItem.diagnoseCode == 1) {//会员流失率高
                    diagnosisItem.activityType = '43';
                    act.activityType = '43';
                    act.actTypeName = '挽回流失会员';
                    act.imgSrc = '../images/index_ls.png';
                } else if (diagnosisItem.diagnoseCode == 2) {//会员数量过少
                    diagnosisItem.activityType = '46';
                    act.activityType = '46';
                    act.actTypeName = '新会员招募';
                    act.imgSrc = '../images/index_xhy.png';
                } else if (diagnosisItem.diagnoseCode == 3) {//回头客较少
                    if (diagnosisItem.configCode.indexOf("COMPOSED_ACTIVITY") != -1) {
                        diagnosisItem.activityType = "51";
                        act.activityType = '51';
                        act.actTypeName = '消费送券';
                        act.imgSrc = "../images/index_xfs.png";
                    } else {
                        diagnosisItem.activityType = "22";
                        act.activityType = '22';
                        act.actTypeName = '消费送券';
                        act.imgSrc = "../images/index_xfs.png";
                    }
                }

                if (diagnosisItem.voucherMinConsume.split("|").length > 0) {
                    diagnosisItem.promoTools = new Array();
                    var voucherMinConsumes = diagnosisItem.voucherMinConsume.split("|");
                    var promoSendRuleMincosts = diagnosisItem.promoSendRuleMincost.split("|");
                    var voucherWorthValues = diagnosisItem.voucherWorthValue.split("|");
                    var voucherRelativeTimes = diagnosisItem.voucherRelativeTime.split("|");
                    var voucherTypes = diagnosisItem.voucherType.split("|");
                    var activityValidDayss = diagnosisItem.activityValidDays.split("|");
                    var configCodes = diagnosisItem.configCode.split("|");
                    var consumeCodes = diagnosisItem.consumeCode.split("|");
                    var crowdDescs = diagnosisItem.crowdDesc.split("|");
                    var crowdGroups = diagnosisItem.crowdGroup.split("|");
                    var crowdGroupIds = diagnosisItem.crowdGroupId.split("|");
                    var crowdNames = diagnosisItem.crowdName.split("|");


                    for (var j = 0; j < voucherMinConsumes.length; j++) {
                        var promTool = {};
                        promTool.voucherMinConsume = voucherMinConsumes[j];
                        promTool.promoSendRuleMincost = promoSendRuleMincosts[j];
                        promTool.voucherWorthValue = voucherWorthValues[j];
                        promTool.voucherRelativeTime = voucherRelativeTimes.length > 2 ? voucherRelativeTimes[j] : voucherRelativeTimes[0];
                        promTool.activityValidDayss = activityValidDayss.length > 2 ? activityValidDayss[j] : activityValidDayss[0];
                        promTool.configCode = configCodes.length > 2 ? configCodes[j] : configCodes[0];
                        promTool.consumeCode = consumeCodes.length > 2 ? consumeCodes[j] : consumeCodes[0];
                        promTool.crowdDesc = crowdDescs.length > 2 ? crowdDescs[j] : crowdDescs[0];
                        promTool.crowdGroup = crowdGroups.length > 2 ? crowdGroups[j] : crowdGroups[0];
                        promTool.crowdGroupId = crowdGroupIds.length > 2 ? crowdGroupIds[j] : crowdGroupIds[0];
                        promTool.crowdName = crowdNames.length > 2 ? crowdNames[j] : crowdNames[0];
                        promTool.voucherType = voucherTypes.length > 2 ? voucherTypes[j] : voucherTypes[0];

                        diagnosisItem.promoTools.push(promTool);
                    }
                }

                diagnosisItem.createPageUrl = self.configInfo.createActPageUrl[diagnosisItem.activityType];
                act.order = self.configInfo.diagnoseOrder[diagnosisItem.diagnoseCode];

                recommendedActs.push(act);
            }
        }


        recommendedActs.sort(function (act1, act2) {
            return act1.order - act2.order;
        });

        for (var i = 0; i < recommendedActs.length; i++) {
            warningContent.push(recommendedActs[i].diagnoseTitle);

        }

        if (result.intelMarketingRecom) {
            if (result.intelMarketingRecom.geneOnPos) {
                warningContent.push("小票营销未开启");
                recommendedActs.push({ activityType: "25", actTypeName: "扫码送券", imgSrc: "../images/index_sm.png" });
            }
        }

        var hasDone = result.optimizedItem.totalOptimizedItemCnt == result.optimizedItem.acceptedOptimizedItemCnt;
        return {
            "totalStartActCnt": totalStartActCnt, "warningContent": warningContent.join("，"),
            "recommendedActs": recommendedActs,
            "hasDone": hasDone
        };
    };

    // 初始化首页信息
    this.initPage = function () {
        var self = this;

        self.initUser();

    };

    this.initUser = function () {
        common.loading("加载中...");
        var serverUrl = App.serverUrl + 　"merchantApp/index/queryUserData.do";
        var self = this;
        var sucFunc = function (result) {
            common.closeLoading();
            if (String(result.success) == 'true') {
                sessionStorageClient.putJSON("user", result.resultObject);
                var authMinusData = {};
                authMinusData = self.getOAuthMinus(authMinusData, result.resultObject.authMinus);
                CommonUtil.render($("#indexPage .footer"), "minus", authMinusData);
                self.initPageData(authMinusData);
                isHaveShop = result.resultObject.isHaveShop == false ? result.resultObject.isHaveShop : true;
            }
        };

        var failFunc = function () {
            common.closeLoading();
        };
        CommonUtil.sendJsonpRequest({ "url": serverUrl, "success": sucFunc, "error": failFunc, "useDefaultLoading": true });
    }

    this.getOAuthMinus = function (result, authMinus) {
        var minusHtml = [];
        var indexCode = [];
        if (authMinus != null && authMinus.length > 0) {
            for (var i = 0; i < authMinus.length; i++) {
                var minus = authMinus[i];
                minusHtml.push(this.configInfo.minus[minus.taskCode]);
                if (minus.taskCode == "app.home") {//首页权限项
                    indexCode = this.getMinuCode(minus.children, indexCode);
                };
            };
            result.minusHtml = minusHtml;
        };
        result.indexCode = indexCode;
        return result;
    }

    this.getMinuCode = function (minus, indexCode) {
        if (minus != null && minus.length > 0) {
            for (var i = 0; i < minus.length; i++) {
                var minu = minus[i];
                indexCode.push(minu.taskCode);
                indexCode = this.getMinuCode(minu.children, indexCode);
            };
        }
        return indexCode;
    }
    // 初始化首页信息
    this.initPageData = function (authMinusData) {
        var self = this;

        if ($.inArray("app.today.data", authMinusData.indexCode) > -1) {
            $("#indexPage .today-data").show();//今日数据显示
            self.initTodayData(authMinusData);
        } else {
            $("#indexPage .today-data").hide();//今日数据显示
        }

        if ($.inArray("app.manage.diagnose", authMinusData.indexCode) > -1) {
            $("#indexPage .diagnose").show();//经营诊断显示
            self.initDiagnoseData();
        } else {
            $("#indexPage .diagnose").hide();//经营诊断隐藏
        }

        if ($.inArray("app.home.moganshan", authMinusData.indexCode) > -1) {
            $("#indexPage #oauthApp").show();//莫干山显示
        } else {
            $("#indexPage #oauthApp").hide();//莫干山隐藏
        }

        if ($.inArray("app.manage.tendency", authMinusData.indexCode) > -1) {
            $("#indexPage .tendency").show();//收入趋势显示
            self.initBusinessTrendChartData();
        } else {
            $("#indexPage .tendency").hide();//收入趋势显示
        }

    };
    this.updateCurrentCountData = function (params) {
        debugger
        var sprice = this.getSplitNumberCompany(params.sprice);
        var spriceNum = sprice[0].split(',').join('');
        if (self.indexPageCountSprice) {
            self.indexPageCountSprice.update(spriceNum);
        } else {
            self.indexPageCountSprice = new CountUp('indexPageCountSprice', spriceNum, 100, 2, 1 ,{
                useEasing: true,
                useGrouping: true,
                separator: ',',
                decimal: '.',
            });
        }
        $("#indexPage #indexPageCountSpriceCompany").text(sprice[1]);
        //收入
        $("#indexPage #indexPageCountIncome").text(params.income);
        //退款
        $("#indexPage #indexPageCountRefund").text(params.refund);
        //刷新时间
        $("#indexPage #indexPageUpdateTime").text('数据更新时间: ' + DateUtil.getDateTime(params.refreshTime));
    }
    this.refreshCountData = function (reset) {
        //刷新统计数据
        var serverUrl = App.serverUrl + 　"merchantApp/index/queryTodayTradeReportData.do";
        var current = new Date();
        var sucFunc = function (result) {
            reset&&reset();
            if (String(result.success) == 'true') {
                self.updateCurrentCountData({ 'sprice': result.resultObject.payAmt, 'income': result.resultObject.income, 'refund': result.resultObject.refundMoney, refreshTime: current });
            } else {

            }
        };

        var failFunc = function () {
            reset&&reset();
        };
        CommonUtil.sendJsonpRequest({ "url": serverUrl, "success": sucFunc, "error": failFunc, "useDefaultLoading": false });
    }
    this.initTodayData = function (authMinusData) {
        common.loading();
        var serverUrl = App.serverUrl + 　"merchantApp/index/queryTodayTradeReportData.do";
        var self = this;
        var current = new Date();
        var sucFunc = function (result) {
            if (String(result.success) == 'true') {
                var resultObject = result.resultObject;
                if (resultObject) {
                    // 渲染模板
                    for (var key in resultObject) {
                        resultObject[key] = CommonUtil.nullValueParser(resultObject, key, '--');
                    }
                    if (authMinusData != null && authMinusData.indexCode.length > 0) {//判断用户权限项
                        resultObject.showNewMember = $.inArray("app.home.todaydata.newmember", authMinusData.indexCode) > -1 ? true : false;
                        resultObject.showManageanalyze = $.inArray("app.home.todaydata.manageanalyze", authMinusData.indexCode) > -1 ? true : false;
                        showManageanalyze = resultObject.showManageanalyze;
                        resultObject.showOrdercount = $.inArray("app.home.todaydata.ordercount", authMinusData.indexCode) > -1 ? true : false;
                        resultObject.showRealmoney = $.inArray("app.home.todaydata.realmoney", authMinusData.indexCode) > -1 ? true : false;
                    };
                    CommonUtil.render($("#indexPage .today-data"), "todayDataTPL", resultObject);
                    self.updateCurrentCountData({ 'sprice': result.resultObject.payAmt, 'income': result.resultObject.income, 'refund': result.resultObject.refundMoney, refreshTime: current });
                }

            } else {
                DialogUtil.dialogWarn(result.msg);
            }
        };

        var failFunc = function () {
            DialogUtil.dialogWarn();
        };
        CommonUtil.sendJsonpRequest({ "url": serverUrl, "success": sucFunc, "error": failFunc, "useDefaultLoading": false });
    };

    this.initDiagnoseData = function () {
        var future = CommonUtil.getUserServiceInfo();
        var self = this;
        var intervalObj = window.setInterval(function () {
            if (future.finish) {
                intervalObj && window.clearInterval(intervalObj);
                if (future.success) {
                    self.queryDiagnoseData(future.data);
                } else {
                    //不影响用户其他操作，可以忽略
                }

            }
        },
            100);
    };
    this.queryDiagnoseData = function (serviceInfo) {
        var serverUrl = App.serverUrl + 　"merchantApp/index/querySmartMarketingData.do";
        var self = this;
        var sucFunc = function (result) {
            if (String(result.success) == 'true') {
                var resultObject = result.resultObject;
                if (resultObject) {
                    self.diagnosisList = resultObject.diagnosisList;
                    var diagnoseData = self.adaptDiagnoseData(resultObject);

                    //如果全部优化过了但是并没有诊断数据，就影藏诊断区域
                    if ((resultObject.optimizedItem.totalOptimizedItemCnt == resultObject.optimizedItem.acceptedOptimizedItemCnt)
                        && (!resultObject.diagnosisList || resultObject.diagnosisList.length == 0)) {
                        $("#indexPage .diagnose").hide();
                    } else {
                        var $diagnose = $("#indexPage .diagnose");
                        $diagnose.hide();

                        if ($diagnose.children().length == 0) {
                            setTimeout(function () {
                                $("#indexPage .diagnose").show();
                                CommonUtil.render($("#indexPage .diagnose"), "diagnoseTPL", diagnoseData);
                            }, 100);
                        } else {
                            $("#indexPage .diagnose").show();
                            CommonUtil.render($("#indexPage .diagnose"), "diagnoseTPL", diagnoseData);
                        }
                        //$("#indexPage .diagnose").show();
                    }
                }

            } else {
                //不影响用户其他操作，可以忽略
            }
        };

        var failFunc = function () {
            DialogUtil.dialogWarn();
        };
        CommonUtil.sendJsonpRequest({
            "url": serverUrl, "success": sucFunc, "error": failFunc,
            "params": {
                "proType": serviceInfo.proServiceType,
            }, "useDefaultLoading": false
        });
    };

    this.initBusinessTrendChartData = function () {
        CommonUtil.render($("#indexPage .tendency"), "businessTrend", {});
        var trendReportChart = echarts.init(document.getElementById("tradeReportChart"), 'normal');
        var option = this.getTrendConfig().option;
        var trendConfig = this.getTrendConfig();
        option.legend.data = trendConfig.legendData['todayPayAmt'];
        option.series = [];
        trendReportChart.setOption(option);

        var serverUrl = App.serverUrl + 　"merchantApp/index/queryTransactionTrendData.do";
        var self = this;
        var endDate = DateUtil.addDays(new Date(), -1);
        var startDate = DateUtil.addDays(new Date(), -7);

        var params = { "startDate": DateUtil.getDateYYYYMMDD(startDate), "endDate": DateUtil.getDateYYYYMMDD(endDate) };


        var sucFunc = function (result) {
            common.closeLoading();
            if (String(result.success) == 'true') {
                var resultObject = result.resultObject;
                if (resultObject && resultObject.length > 0) {
                    var xAxis = [];
                    var series = [];
                    var seriesItem1 = [];
                    for (var i = 0; i < resultObject.length; i++) {
                        var year = resultObject[i].bizDate.substring(0, 4);
                        var month = resultObject[i].bizDate.substring(4, 6);
                        var day = resultObject[i].bizDate.substring(6, 8);


                        var bizDate = new Date();
                        bizDate.setFullYear(year);
                        bizDate.setMonth(month - 1);
                        bizDate.setDate(day);


                        xAxis.push(DateUtil.format(bizDate, 'M-d'));
                        seriesItem1.push(resultObject[i].todayPayAmt);
                    }

                    if (seriesItem1.length > 0) {
                        series.push(seriesItem1);
                    }

                    option.yAxis[0].name = trendConfig.yAxisNames['todayPayAmt'];
                    option.legend.data = trendConfig.legendData['todayPayAmt'];
                    option.xAxis[0].data = xAxis;
                    option.series = [];
                    for (var i = 0; i < series.length; i++) {
                        var serie = {
                            name: trendConfig.seriesNames['todayPayAmt'][i], type: 'line', smooth: true,
                            data: series[i],
                            areaStyle: { normal: {} }
                        };
                        option.series.push(serie);
                    }
                    trendReportChart.setOption(option);
                }

            } else {
                DialogUtil.dialogWarn(result.msg);
            }
        };

        var failFunc = function () {
            common.closeLoading();
            DialogUtil.dialogWarn();
        };
        CommonUtil.sendJsonpRequest({ "url": serverUrl, "success": sucFunc, "error": failFunc, "params": params, "useDefaultLoading": false });
    };

    this.getCreateActParam = function (activityType) {
        //先从诊断里面找
        for (var i = 0; i < this.diagnosisList.length; i++) {
            if (activityType == this.diagnosisList[i].activityType) {
                return this.diagnosisList[i];
            }
        }

        //诊断没找到再直接走配置
        var param = { "activityType": activityType, "createPageUrl": this.configInfo.createActPageUrl[activityType] };
        return param;

    };

    this.gotoOAuthCode = function () {
        //请求bmserver获取授权码
        var serverUrl = App.serverUrl + 　"app/oauth/getOAuthCode.do";
        var sucFunc = function (result) {

            common.closeLoading();
            if (String(result.success) == 'true') {
                var resultObject = result.resultObject;
                //跳转到crossairw服务，进行授权验证
                var oauthUrl = App.oauthUrl + resultObject;
                // window.location.href = oauthUrl;
                // alert("授权路径:" + oauthUrl);
                // DialogUtil.dialogWarn("授权路径:" + oauthUrl);
                AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
                    url: oauthUrl,
                    target: "server",
                    param: {
                        title: {
                            title: '  ',
                            color: '#333333',
                            background: '#ffffff'
                        }
                    }
                });

            } else {
                DialogUtil.dialogWarn(result.msg);
            }
        };

        var failFunc = function () {
            common.closeLoading();
            DialogUtil.dialogWarn();
        };
        CommonUtil.sendJsonpRequest({ "url": serverUrl, "success": sucFunc, "error": failFunc, "params": null, "useDefaultLoading": false });

    };

    //莫干山获取APP授权码
    this.getOAuthCode = function () {
        var self = this;
        //请求bmserver获取授权码
        var serverUrl = App.serverUrl + 　"serviceMarket/checkAuthToken.do";
        var sucFunc = function (result) {
            common.closeLoading();
            if (String(result.success) == 'true') {
                self.gotoOAuthCode();
            } else {
                var toAuthorizeUrl = App.bmwServiceUrl + '?' + App.urlParam + '#/toAuthorize';
                AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
                    url: toAuthorizeUrl,
                    target: "server",
                    param: {
                        title: {
                            title: '去授权',
                            color: '#333333',
                            background: '#ffffff'
                        }
                    }
                });
            }
        };

        var failFunc = function () {
            common.closeLoading();
            DialogUtil.dialogWarn();
        };
        CommonUtil.sendJsonpRequest({ "url": serverUrl, "success": sucFunc, "error": failFunc, "params": null, "useDefaultLoading": true });

    }

        //扫码绑定
    this.scan=function() {
           var _this=this;
            try {
            //   this.scanCallback('SN111111003');
            AppUtil.call(AppUtil.APIS.SCAN,{}, function(response) {
                if (response && (response.success===true || response.success==='true')) {
                  var code = response.resultObject;
                  //判断二维码是否正确
                  var decollator = "?sn=";
                  if (code && code.indexOf(decollator) !==-1) {
                    code = code.substring(
                      code.indexOf(decollator)+decollator.length
                    );
                    _this.scanCallback(code);
                  } else {
                    DialogUtil.dialogConfirm("暂不支持识别");
                  }
                }
                else if(response && response.code && response.code=='-10'){
                  //未扫码，返回，不处理
                }
                else {
                    DialogUtil.dialogWarn("扫码失败");
                }
              });
            } catch (err) {
                DialogUtil.dialogWarn("扫码异常"+err);
            }
    };
    this.scanCallback=function(code){

        var serverUrl = App.serverUrl + 　"app/voice/scanBindQr.do?sn="+code;
        var sucFunc = function (res) {
            if (res.success) {
                setTimeout(function(){
                    if(res.resultObject.isBinded){
                        if(res.code==-2){
                        //没有权限
                        AppUtil.call(AppUtil.APIS.PUSH_WINDOW,
                            {
                                url: 'vuepages/index.html#/qrCodeSound/authNone',
                                target: 'local',
                                param: {
                                    title: null
                                }
                            });
                        }else{
                            AppUtil.call(AppUtil.APIS.PUSH_WINDOW,
                                {
                                    url: "vuepages/index.html#/qrCodeSound/mainSettings",
                                    target: 'local',
                                    suffixParams:"sn="+res.resultObject.sn+"&type="+res.resultObject.type,
                                    param: {
                                        title: null
                                    }
                                });
                        }
                    }else{
                    //没有绑定
                        AppUtil.call(AppUtil.APIS.PUSH_WINDOW,
                            {
                                url: 'vuepages/index.html#/qrCodeSound/bindingStore',
                                target: 'local',
                                suffixParams:"sn="+res.resultObject.sn+"&type="+res.resultObject.type,
                                param: {
                                    title: null
                                }
                            });
                    }
                },300);
              }else if(res.code==-2){
                setTimeout(function(){
                  //没有权限
                  AppUtil.call(AppUtil.APIS.PUSH_WINDOW,
                    {
                        url: 'vuepages/index.html#/qrCodeSound/authNone',
                        target: 'local',
                        param: {
                            title: null
                        }
                    });
                },300);
              }else{
                DialogUtil.dialogConfirm(res.msg);
              }
        };

        var failFunc = function () {
            DialogUtil.dialogWarn("调用解析二维码接口失败");
        };
        CommonUtil.sendJsonpRequest({ "url": serverUrl, "success": sucFunc, "error": failFunc, "useDefaultLoading": true });
    };
};
